package com.spzx.order.receiver;

import com.rabbitmq.client.Channel;
import com.spzx.common.rabbit.constant.MqConst;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * Description:
 * 测试rabbitmq，测试消费者端是否能够接收消息
 * @author Yanxinhao on 2024/12/27
 */


@Slf4j
@Component
public class TestReceiver {
    /**
     * 【测试消费者】
     * 测试一下消费者能不能正确监听到对应的队列
     * 并且消费消息
     * 通过@RabbitListener给当前整个方法设置一个rabbitmq的监听器，并且配置与之绑定的交换机、队列、路由键
     * 交换机：spzx.exchange.test
     * 队列:spzx.queue.test
     * 绑定路由键:spzx.routing.test
     * @param content
     * @param message
     */
    @RabbitListener( bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_TEST),//交换机可以默认不写durable = "true"，因为交换机默认就是持久化的
            value = @Queue(value = MqConst.QUEUE_TEST,durable = "true"),
            key = MqConst.ROUTING_TEST
    ))
    public void test(String content, Message message){
        log.info("test测试端接收到消息:{}",content);
        log.info("test测试端接收到消息:{}",new String(message.getBody()));
    }

    /**
     * 测试确认消息
     * @param message
     * @param channel
     */
    @RabbitListener( bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_TEST),
            value = @Queue(value = MqConst.QUEUE_CONFIRM,durable = "true"),
            key = MqConst.ROUTING_CONFIRM
    ))
    @SneakyThrows //Lombok的注解，表示如果方法体中有异常，直接抛出，不用自己try catch
    public void confirm(Message message, Channel channel){
        log.info("confirm测试端接收到消息:{}",new String(message.getBody()));
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }



}